package com.guiwu.controller;

import com.guiwu.entity.Item;
import com.guiwu.entity.User;
import com.guiwu.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/item")
public class ItemController {
    @Autowired
    private ItemService itemService;

    /**
     * 获取当前用户所有物品
     */
    @GetMapping("/list")
    public List<Item> list(@AuthenticationPrincipal User user) {
        return itemService.getAllItemsByUser(user.getId());
    }

    /**
     * 按分类获取物品
     */
    @GetMapping("/by-category")
    public List<Item> byCategory(@AuthenticationPrincipal User user, @RequestParam Long categoryId) {
        return itemService.getItemsByCategory(user.getId(), categoryId);
    }

    /**
     * 按名称模糊搜索
     */
    @GetMapping("/search")
    public List<Item> search(@AuthenticationPrincipal User user, @RequestParam String keyword) {
        return itemService.searchItems(user.getId(), keyword);
    }

    /**
     * 新增物品
     */
    @PostMapping("/add")
    public boolean add(@AuthenticationPrincipal User user, @RequestBody Item item) {
        item.setUserId(user.getId());
        return itemService.save(item);
    }

    /**
     * 删除物品
     */
    @PostMapping("/delete")
    public boolean delete(@AuthenticationPrincipal User user, @RequestParam Long id) {
        Item item = itemService.getById(id);
        if (item != null && item.getUserId().equals(user.getId())) {
            return itemService.removeById(id);
        }
        return false;
    }

    /**
     * 更新物品
     */
    @PostMapping("/update")
    public boolean update(@AuthenticationPrincipal User user, @RequestBody Item item) {
        Item dbItem = itemService.getById(item.getId());
        if (dbItem != null && dbItem.getUserId().equals(user.getId())) {
            item.setUserId(user.getId());
            return itemService.updateById(item);
        }
        return false;
    }
} 